﻿using UnityEngine;

namespace UnityMovementAI
{
    public class Wander2Unit : MonoBehaviour
    {
        SteeringBasics steeringBasics;
        Wander2 wander;

        [Header("徘徊")]
        public Transform tf_wanderRawTarget = null;
        private Vector3 v3_wanderRawTarget;
        public float fWanderRawRange = 10f;


        [Header("碰撞后懵逼时长")]
        public float fWaitTime = 1f;
        private float fWaitTimer = 0f;
        [Header("运行时")]
        public bool bIsActive = true;
        public bool bWait = false;

        void Start()
        {
            steeringBasics = GetComponent<SteeringBasics>();
            wander = GetComponent<Wander2>();

            if (tf_wanderRawTarget == null) v3_wanderRawTarget = gameObject.transform.position;
            else v3_wanderRawTarget = tf_wanderRawTarget.position;
        }


        void FixedUpdate()
        {
            if (!bIsActive) return;

            MoveUpdate();
        }


        # region "Update拆解"

        Vector3 lastAccel = Vector3.zero;
        void MoveUpdate(){
            Vector3 accel;
            if (bWait){ // 如果处于等待状态, 就等待一会后再往回走, 否则就正常往前走
                fWaitTimer+=Time.deltaTime;
                if (fWaitTimer>fWaitTime){
                    fWaitTimer = 0f;
                    bWait = false;
                    accel = v3_wanderRawTarget - transform.position - lastAccel.normalized;
                }
                else{
                    steeringBasics.Stand();
                    steeringBasics.LookWhereYoureGoing();
                    return;
                } 
            } else accel = wander.GetSteering();
            lastAccel = accel;
            steeringBasics.Steer(accel);
            steeringBasics.LookWhereYoureGoing();
            if (!CheckInWanderRawTargetRange()){// 走出了范围就停一会, 再往回走
                bWait = true;
            }
        }

        # endregion


        public void SetActive(bool bActive)
        {
            bIsActive = bActive;
        }

        private void OnCollisionEnter2D(Collision2D other) {
            if (bWait) return;
            bWait = true;
        }

        private bool CheckInWanderRawTargetRange(){
            return Vector3.Distance(transform.position, v3_wanderRawTarget) < fWanderRawRange;
        }
    }

}